import React, { useRef, useEffect, useState } from "react";
import io from "socket.io-client";
import { useNavigate } from "react-router-dom";

const SIGNAL_SERVER_URL = "http://localhost:3001"; // 或 4000
let pc = null;

export default function List() {
  const localVideo = useRef(null);
  const remoteVideo = useRef(null);
  const socketRef = useRef(null);
  const [calling, setCalling] = useState(false);
  const [waiting, setWaiting] = useState(false);
  const [muted, setMuted] = useState(false);
  const [volume, setVolume] = useState(1);
  const [callTime, setCallTime] = useState(0); // 秒
  const [cameraOn, setCameraOn] = useState(true);
  const navigate = useNavigate();
  const [showPlayBtn, setShowPlayBtn] = useState(false);
  const audioRef = useRef(null);
  const [showChat, setShowChat] = useState(false);

  // 假数据
  const doctorName = "刘医生";
  const doctorTitle = "认证精神科医生";
  const doctorAvatar = "https://randomuser.me/api/portraits/men/32.jpg";
  const selfAvatar = "https://randomuser.me/api/portraits/women/44.jpg";

  useEffect(() => {
    let timer;
    if (calling) {
      timer = setInterval(() => setCallTime(t => t + 1), 1000);
    } else {
      setCallTime(0);
    }
    return () => timer && clearInterval(timer);
  }, [calling]);

  useEffect(() => {
    navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(stream => {
      localVideo.current.srcObject = stream;
      pc = new RTCPeerConnection();
      stream.getTracks().forEach(track => pc.addTrack(track, stream));
      pc.ontrack = (event) => {
        remoteVideo.current.srcObject = event.streams[0];
      };
      socketRef.current = io(SIGNAL_SERVER_URL);
      socketRef.current.on("signal", async (data) => {
        if (data.type === "accept") {
          setWaiting(false);
          setCalling(true);
          const offer = await pc.createOffer();
          await pc.setLocalDescription(offer);
          socketRef.current.emit("signal", { type: "offer", offer });
        } else if (data.type === "answer") {
          await pc.setRemoteDescription(new RTCSessionDescription(data.answer));
        } else if (data.type === "candidate") {
          try {
            await pc.addIceCandidate(new RTCIceCandidate(data.candidate));
          } catch (e) {}
        }
      });
      pc.onicecandidate = (event) => {
        if (event.candidate) {
          socketRef.current.emit("signal", { type: "candidate", candidate: event.candidate });
        }
      };
    });
    return () => {
      if (socketRef.current) socketRef.current.disconnect();
      if (pc) pc.close();
    };
  }, []);

  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.muted = false;
      audioRef.current.play().catch(() => {
        setShowPlayBtn(true);
      });
    }
    return () => {
      if (audioRef.current) {
        audioRef.current.pause();
        audioRef.current.currentTime = 0;
      }
    };
  }, []);

  useEffect(() => {
    if (calling && audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
    }
  }, [calling]);

  useEffect(() => {
    const tryPlay = () => {
      if (audioRef.current) {
        audioRef.current.muted = false;
        audioRef.current.play();
      }
    };
    window.addEventListener('click', tryPlay, { once: true });
    return () => window.removeEventListener('click', tryPlay);
  }, []);

  const call = () => {
    if (audioRef.current) {
      audioRef.current.muted = false;
      audioRef.current.play();
    }
    setWaiting(true);
    socketRef.current.emit("signal", { type: "call" });
  };

  const hangup = () => {
    setCalling(false);
    setWaiting(false);
    if (pc) {
      pc.close();
      pc = null;
    }
    navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(stream => {
      localVideo.current.srcObject = stream;
      pc = new RTCPeerConnection();
      stream.getTracks().forEach(track => pc.addTrack(track, stream));
      pc.ontrack = (event) => {
        remoteVideo.current.srcObject = event.streams[0];
      };
      pc.onicecandidate = (event) => {
        if (event.candidate) {
          socketRef.current.emit("signal", { type: "candidate", candidate: event.candidate });
        }
      };
    });
    navigate("/home");
  };

  // 时间格式 mm:ss
  const formatTime = (s) => `${String(Math.floor(s/60)).padStart(2, "0")}:${String(s%60).padStart(2, "0")}`;

  // 音量调节
  const handleVolume = (e) => {
    setVolume(e.target.value);
    if (remoteVideo.current) remoteVideo.current.volume = e.target.value;
  };

  // 静音
  const toggleMute = () => {
    setMuted(m => !m);
    if (remoteVideo.current) remoteVideo.current.muted = !muted;
  };

  // 摄像头开关
  const toggleCamera = () => {
    setCameraOn(on => {
      if (localVideo.current && localVideo.current.srcObject) {
        localVideo.current.srcObject.getVideoTracks().forEach(track => {
          track.enabled = !on;
        });
      }
      return !on;
    });
  };

  const handleManualPlay = () => {
    if (audioRef.current) {
      audioRef.current.muted = false;
      audioRef.current.play();
      setShowPlayBtn(false);
    }
  };

  return (
    <div style={{ position: "relative", width: "100vw", height: "100vh", background: "#fff", overflow: "hidden" }}>
      {/* 顶部医生信息 */}
      <div style={{ position: "absolute", top: 32, width: "100%", textAlign: "center", zIndex: 10 }}>
        <div style={{ fontSize: 28, color: "#5a4326", fontWeight: 600 }}>{doctorName}</div>
        <div style={{ fontSize: 18, color: "#a08c6b", marginTop: 4 }}>{doctorTitle}</div>
      </div>
      {/* 大窗口：对方画面/医生头像 */}
      <video
        ref={remoteVideo}
        autoPlay
        playsInline
        muted={muted}
        style={{
          width: "100vw",
          height: "100vh",
          objectFit: "cover",
          background: `url(${'../public/ljx/6.jpg'}) center/cover no-repeat`,
          filter: "brightness(0.98)",
        }}
      />
      {/* 右上角：自己画面小窗口 */}
      <div style={{ position: "absolute", top: 24, right: 24, width: 90, height: 90, borderRadius: 16, overflow: "hidden", boxShadow: "0 2px 8px rgba(0,0,0,0.18)", zIndex: 20 }}>
        {cameraOn ? (
          <video
            ref={localVideo}
            autoPlay
            playsInline
            muted
            style={{ width: "100%", height: "100%", objectFit: "cover", background: `url(${'/ljx/14.jpg'}) center/cover no-repeat` }}
          />
        ) : (
          <img src="/ljx/14.jpg" alt="默认头像" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
        )}
      </div>
      {/* 左侧音量条和静音按钮 */}
      <div style={{ position: "absolute", left: 16, top: "30%", zIndex: 20, display: "flex", flexDirection: "column", alignItems: "center" }}>
        <input type="range" min={0} max={1} step={0.01} value={volume} onChange={handleVolume} style={{ writingMode: "bt-lr", width: 8, height: 120, marginBottom: 12 }} />
        <button onClick={toggleMute} style={{ background: "#fff", border: "none", borderRadius: "50%", width: 36, height: 36, boxShadow: "0 2px 6px rgba(0,0,0,0.12)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 20, color: "#5a4326", cursor: "pointer" }}>{muted ? "🔇" : "🔊"}</button>
      </div>
      {/* 通话时长 */}
      {calling && (
        <div style={{ position: "absolute", top: "85%", left: "50%", transform: "translate(-50%, -50%)", background: "rgba(0,0,0,0.18)", color: "#fff", borderRadius: 16, padding: "4px 18px", fontSize: 18, zIndex: 30, display: "flex", alignItems: "center" }}>
          <span style={{ marginRight: 6 }}></span>{formatTime(callTime)}
        </div>
      )}
      {/* 等待对方接听提示 */}
      {waiting && (
        <div
          style={{
            position: "absolute",
            top: "85%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            color: "#bfc2c7",
            fontSize: 18,
            fontWeight: 200,
            zIndex: 50,
            textShadow: "0 2px 8px rgba(0,0,0,0.18)"
          }}
        >
          等待对方接受邀请...
        </div>
      )}
      {/* 底部按钮区 */}
      <div style={{ position: "absolute", bottom: 36, width: "100%", display: "flex", justifyContent: "center", alignItems: "center", zIndex: 30 }}>
        <button onClick={toggleCamera} style={{ width: 56, height: 56, borderRadius: "50%", background: "#4e3a23", border: "none", color: "#fff", fontSize: 26, marginRight: 40, display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 2px 8px rgba(0,0,0,0.18)", cursor: "pointer" }}>
          {cameraOn ? "🎥" : "🚫"}
        </button>
        {!calling && (
          <button
            onClick={call}
            style={{ width: 80, height: 80, borderRadius: "50%", background: "#ff9800", border: "none", color: "#fff", fontSize: 38, display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 4px 16px rgba(255,152,0,0.18)", margin: "0 40px", cursor: waiting ? "not-allowed" : "pointer" }}
            disabled={waiting}
          >
            📞
          </button>
        )}
        {calling && (
          <button
            onClick={hangup}
            style={{ width: 80, height: 80, borderRadius: "50%", background: "#e53935", border: "none", color: "#fff", fontSize: 38, display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 4px 16px rgba(229,57,53,0.18)", margin: "0 40px", cursor: "pointer" }}
          >
            📞
          </button>
        )}
        <button style={{ width: 56, height: 56, borderRadius: "50%", background: "#4e3a23", border: "none", color: "#fff", fontSize: 26, marginLeft: 40, display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 2px 8px rgba(0,0,0,0.18)", cursor: "pointer" }}>
          💬
        </button>
      </div>
      {/* 右下角叠加方块图标 */}
      <div
        style={{
          position: "absolute",
          bottom: 120,
          right: 24,
          width: 40,
          height: 40,
          zIndex: 100,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          background: "rgba(0,0,0,0.18)",
          borderRadius: 12
        }}
        onClick={() => {
          if (remoteVideo.current) {
            remoteVideo.current.requestPictureInPicture();
          }
        }}
      >
        <svg width="28" height="28" viewBox="0 0 40 40">
          <rect x="8" y="8" width="16" height="16" rx="3" fill="none" stroke="#fff" strokeWidth="2.5"/>
          <rect x="16" y="16" width="16" height="16" rx="3" fill="none" stroke="#fff" strokeWidth="2.5"/>
        </svg>
      </div>
      <audio ref={audioRef} src="/ring.mp3" autoPlay loop />
      {showChat && (
        <div style={{
          position: "fixed",
          top: 0, left: 0, right: 0, bottom: 0,
          background: "rgba(0,0,0,0.18)",
          zIndex: 9999,
          display: "flex",
          alignItems: "center",
          justifyContent: "center"
        }}>
          <div style={{
            width: 380,
            height: 600,
            background: "#f7f7f7",
            borderRadius: 24,
            boxShadow: "0 4px 32px rgba(0,0,0,0.10)",
            display: "flex",
            flexDirection: "column",
            overflow: "hidden"
          }}>
            {/* 顶部栏 */}
            <div style={{
              height: 60,
              background: "#fff",
              borderTopLeftRadius: 24,
              borderTopRightRadius: 24,
              display: "flex",
              alignItems: "center",
              padding: "0 16px",
              boxShadow: "0 2px 8px rgba(0,0,0,0.06)",
              borderBottom: "1px solid #f0f0f0"
            }}>
              <img src="/ljx/doctor-avatar.jpg" alt="医生" style={{width: 38, height: 38, borderRadius: "50%", marginRight: 12}} />
              <div>
                <div style={{fontWeight: 600, fontSize: 18, color: "#333"}}>刘医生</div>
                <div style={{fontSize: 12, color: "#a08c6b"}}>认证精神科医生</div>
              </div>
              <button onClick={() => setShowChat(false)} style={{marginLeft: "auto", background: "none", border: "none", fontSize: 24, color: "#a08c6b", cursor: "pointer"}}>×</button>
            </div>
            {/* 消息区 */}
            <div style={{flex: 1, overflowY: 'auto', padding: '18px 12px 18px 12px', background: '#f7f7f7'}}>
              {/* 时间分割线 */}
              <div style={{textAlign: "center", color: "#b0b0b0", fontSize: 12, margin: "16px 0"}}>今天 上午 10:20</div>
              {/* 医生消息 */}
              <div style={{display: "flex", alignItems: "flex-end", marginBottom: 10}}>
                <img src="/ljx/doctor-avatar.jpg" alt="医生" style={{width: 32, height: 32, borderRadius: "50%", marginRight: 8}} />
                <div style={{
                  background: "#fff",
                  color: "#333",
                  borderRadius: "0 16px 16px 16px",
                  padding: "10px 16px",
                  maxWidth: 220,
                  fontSize: 16,
                  boxShadow: "0 1px 2px #ececec"
                }}>
                  你好，我是刘医生。
                </div>
              </div>
              {/* 用户消息 */}
              <div style={{display: "flex", alignItems: "flex-end", justifyContent: "flex-end", marginBottom: 10}}>
                <div style={{
                  background: "#95ec69",
                  color: "#222",
                  borderRadius: "16px 0 16px 16px",
                  padding: "10px 16px",
                  maxWidth: 220,
                  fontSize: 16,
                  boxShadow: "0 1px 2px #ececec"
                }}>
                  医生，我最近很焦虑。
                </div>
                <img src="/ljx/self-avatar.jpg" alt="我" style={{width: 32, height: 32, borderRadius: "50%", marginLeft: 8}} />
              </div>
              {/* 医生消息 */}
              <div style={{display: "flex", alignItems: "flex-end", marginBottom: 10}}>
                <img src="/ljx/doctor-avatar.jpg" alt="医生" style={{width: 32, height: 32, borderRadius: "50%", marginRight: 8}} />
                <div style={{
                  background: "#fff",
                  color: "#333",
                  borderRadius: "0 16px 16px 16px",
                  padding: "10px 16px",
                  maxWidth: 220,
                  fontSize: 16,
                  boxShadow: "0 1px 2px #ececec"
                }}>
                  你可以详细说说是什么让你焦虑吗？
                </div>
              </div>
              {/* 用户消息 */}
              <div style={{display: "flex", alignItems: "flex-end", justifyContent: "flex-end", marginBottom: 10}}>
                <div style={{
                  background: "#95ec69",
                  color: "#222",
                  borderRadius: "16px 0 16px 16px",
                  padding: "10px 16px",
                  maxWidth: 220,
                  fontSize: 16,
                  boxShadow: "0 1px 2px #ececec"
                }}>
                  主要是工作压力大，睡眠不好。
                </div>
                <img src="/ljx/self-avatar.jpg" alt="我" style={{width: 32, height: 32, borderRadius: "50%", marginLeft: 8}} />
              </div>
            </div>
            {/* 输入区 */}
            <div style={{
              padding: "10px 12px",
              background: "#f7f7f7",
              borderBottomLeftRadius: 24,
              borderBottomRightRadius: 24,
              display: "flex",
              alignItems: "center",
              borderTop: "1px solid #eee"
            }}>
              <span style={{fontSize: 22, color: "#888", marginRight: 8, cursor: "pointer"}}>😊</span>
              <input type="text" placeholder="请输入..." style={{
                flex: 1,
                border: "none",
                outline: "none",
                borderRadius: 18,
                padding: "10px 16px",
                fontSize: 16,
                background: "#fff",
                color: "#333",
                marginRight: 8
              }} />
              <button style={{
                background: "#95ec69",
                border: "none",
                color: "#fff",
                fontSize: 18,
                borderRadius: 18,
                padding: "6px 18px",
                cursor: "pointer"
              }}>发送</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}